package com.yuyou.tas.report.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.tas.report.mapper.ExamModelActivityMapper;
import com.yuyou.tas.report.service.IExamModelRangeService;
import com.yuyou.tas.report.service.IExamModelService;
import com.yuyou.tas.report.service.IExamModelWordRelService;
import com.yuyou.tas.report.vo.req.ExamModelActivityAdd;
import com.yuyou.tas.report.vo.req.ExamModelActivityEdit;
import com.yuyou.tas.report.vo.req.ExamModelAdd;
import com.yuyou.tas.report.vo.req.ExamModelEdit;
import com.yuyou.tas.report.vo.resp.ExamModelBlockVo;
import com.yuyou.tas.report.vo.resp.ExamModelDetailVo;
import com.yuyou.tas.report.vo.resp.ExamModelSimpleVo;
import com.yuyou.tas.report.vo.resp.StudentRecordVo;
import com.yuyou.tas.service.api.report.dto.ExamModelActivityDTO;
import com.yuyou.tas.service.api.report.dto.ExamModelDTO;
import com.yuyou.tas.service.api.report.entity.ExamModelActivity;
import com.yuyou.tas.service.api.report.entity.ExamModelWordRel;
import com.yuyou.tas.util.bean.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value="ExamModelController",description="试卷模板接口")
@Validated
@RestController
@RequestMapping(value = "/api/examModel/")
public class ExamModelController extends BaseController{


    @Autowired
    private IExamModelService examModelService;

    @Autowired
    private ExamModelActivityMapper examModelActivityMapper;

    @Autowired
    private IExamModelWordRelService examModelWordRelService;

    @Autowired
    private IExamModelRangeService examModelRangeService;

    @ApiOperation(value = "试卷模板列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(name = "examModelActivityId", value = "活动id", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "模板关键字", paramType = "query"),
            @ApiImplicitParam(name = "dataSubject", value = "科目", paramType = "query"),
            @ApiImplicitParam(name = "baseLevelId", value = "层级", paramType = "query"),
            @ApiImplicitParam(name = "rangeType", value = "类型 0:标准, 1:自定义", paramType = "query"),
            @ApiImplicitParam(name = "baseSectionId", value = "年级", paramType = "query"),
            @ApiImplicitParam(name = "baseTrimesterId", value = "学期ID", paramType = "query"),
            @ApiImplicitParam(name = "isRelated", value = "是否是引用的 0 :否，1 :是", paramType = "query")})
    @RequestMapping(value = "/examModelList", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<List<ExamModelDTO>> examModelList(HttpServletRequest request,
                                                          @Validated @ModelAttribute PageParams pageParams,
                                                          Long examModelActivityId,
                                                          String name,
                                                          Long dataSubject,
                                                          Long baseLevelId,
                                                          Integer rangeType,
                                                          Long baseSectionId,
                                                          Long baseTrimesterId,
                                                          Integer isRelated
                                                           )  {
        LoginRedisObj obj = this.getUserObj(request);
        Long authOrganizationId=obj.getOrganizationId();

        Map<String, Object> conditions = new HashMap<>();
        Pagination<ExamModelDTO> queryPgn = new Pagination<>();
        conditions.put("authOrganizationId", authOrganizationId);
        conditions.put("examModelActivityId", examModelActivityId);
        conditions.put("name", name);
        conditions.put("dataSubject", dataSubject);
        conditions.put("baseLevelId", baseLevelId);
        conditions.put("rangeType", rangeType);
        conditions.put("baseSectionId", baseSectionId);
        conditions.put("baseTrimesterId", baseTrimesterId);
        conditions.put("isRelated", null == isRelated ? 0 : isRelated);
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);

        int total = examModelService.findExamModelCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            List<ExamModelDTO> list = examModelService.findExamModelPageList(queryPgn);
            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }

    @ApiOperation(value = "删除试卷模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷模板ID", paramType = "query", required = true)})
    @RequestMapping(value = "/deleteExamModel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<String> deleteExamModel(@NotNull(message = "试卷模板ID") Long id) {

        examModelService.deleteExamModelById(id);
        return ReturnResult.success("OK");
    }

    @ApiOperation(value = "新建试卷模板")
    @RequestMapping(value = "/addExamModel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ResBoolSimpleInfo> addExamModel(@Validated @ModelAttribute ExamModelAdd examModelAdd,
                                               HttpServletRequest request) {

        LoginRedisObj loginObj = this.getUserObj(request);
        ResBoolSimpleInfo res = examModelService.addExamModel(examModelAdd, loginObj);
        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }

    @ApiOperation(value = "试卷模板详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷模板ID", paramType = "query", required = true)})
    @RequestMapping(value = "/detailExamModel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ExamModelDetailVo> detailExamModel(@NotNull(message = "试卷模板ID") Long id,
                                                           HttpServletRequest request) {
        LoginRedisObj loginObj = this.getUserObj(request);
        ExamModelDetailVo examModelDetailVo = examModelService.detailExamModel(id, loginObj);
        return ReturnResult.success(examModelDetailVo);
    }

    @ApiOperation(value = "编辑试卷模板")
    @RequestMapping(value = "/editExamModel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<String> editExamModel(@Validated @ModelAttribute ExamModelEdit examModelEdit,
                                              HttpServletRequest request) {

        LoginRedisObj loginObj = this.getUserObj(request);
        ResBoolSimpleInfo<String> res = examModelService.editExamModel(examModelEdit, loginObj);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),res.getData());
    }

    @ApiOperation(value = "模板存在适用范围设置")
    @RequestMapping(value = "/existExamModelRange", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<Integer> existExamModelRange(@RequestParam(value = "id")@NotNull(message = "试卷模板ID") Long id) {

//        LoginRedisObj loginObj = this.getUserObj(request);
        Integer count = examModelRangeService.countByExamModelId(id);
        return ReturnResult.success(count);
    }

    @ApiOperation(value = "添加试卷模块")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examModelId", value = "试卷模板ID", paramType = "query", required = true),
            @ApiImplicitParam(name = "examModelBlockAddJson", value = "模块json", paramType = "query", required = true)})
    @RequestMapping(value = "/addBlock2ExamModel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ResBoolSimpleInfo<String>> addBlock2ExamModel(@RequestParam(value = "examModelId")@NotNull(message = "模板id不能为空") Long examModelId,
                                                                      @RequestParam(value = "examModelBlockAddJson")@NotEmpty(message = "examModelBlockAddJson 不能为空") String examModelBlockAddJson,
                                                                      HttpServletRequest request) {

        List<ExamModelBlockVo> examModelBlockVoList = JSONObject.parseObject(examModelBlockAddJson, new TypeReference<List<ExamModelBlockVo>>(){});
        ResBoolSimpleInfo res = examModelService.addBlock2ExamModel(examModelId, examModelBlockVoList);
        return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), res.getData());
    }


    @ApiOperation(value = "模块列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examModelId", value = "试卷模板ID", paramType = "query", required = true)})
    @RequestMapping(value = "/examModelBlockList", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<List<ExamModelBlockVo>> examModelBlockList(@RequestParam(value = "examModelId")@NotNull(message = "模板id不能为空") Long examModelId,
                                                                      HttpServletRequest request) {

        List<ExamModelBlockVo> examModelBlockVoList = examModelService.examModelBlockList(examModelId);
        return ReturnResult.success(examModelBlockVoList);
    }


    @ApiOperation(value = "添加模板使用范围")
    @RequestMapping(value = "/addLessonClass2ExamModel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ResBoolSimpleInfo<String>> addLessonClass2ExamModel(@RequestParam(value = "examModelId")@NotNull(message = "模板id不能为空") Long examModelId,
                                                                            @RequestParam(value = "lessonClassIdsStr")@NotBlank(message = "班级ids 不能为空") String lessonClassIdsStr,
                                                                            HttpServletRequest request) {

        LoginRedisObj loginObj = this.getUserObj(request);
        List<Long> lessonClassIds = Arrays.asList(lessonClassIdsStr.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        ResBoolSimpleInfo<String> res = examModelService.addLessonClass2ExamModel(examModelId, lessonClassIds, loginObj);
        return ReturnResult.success(res);
    }

    @ApiOperation(value = "添加模板文案")
    @RequestMapping(value = "/setExamModelWordRel", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ResBoolSimpleInfo<String>> addExamModelWord(
    		@NotNull(message = "模板id不能为空") Long examModelId,Long examModelWordId,
    		HttpServletRequest request) {

        LoginRedisObj loginObj = this.getUserObj(request);

        ExamModelWordRel record=new ExamModelWordRel();
        record.setAuthOrganizationId(loginObj.getOrganizationId());
        record.setExamModelId(examModelId);
        record.setExamModelWordId(examModelWordId);
        ResBoolSimpleInfo<String> res=examModelWordRelService.setUp(record);
        
        return ReturnResult.success(res);
    }
    
    
    @ApiOperation(value = "试卷模板列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classId", value = "班级ID", paramType = "query", required = true),
            @ApiImplicitParam(name = "levelId", value = "班型", paramType = "query"),
            @ApiImplicitParam(name = "range_type", value = "试卷类型", paramType = "query"),
            @ApiImplicitParam(name = "timeType", value = "期类型", paramType = "query")})
    @RequestMapping(value = "/classExamModelList", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<List<ExamModelSimpleVo>> classExamModelList(@RequestParam(value = "classId")@Validated @NotNull(message = "班级ID不能为空") Long classId,
                                                                    @RequestParam(value = "activityId")@Validated @NotNull(message = "活动ID不能为空") Long activityId,
                                                                    @RequestParam(value = "levelId" , required = false) Long levelId,
                                                                    @RequestParam(value = "range_type" , required = false) Integer range_type,
                                                                    @RequestParam(value = "timeType" , required = false) Integer timeType,
                                                                    HttpServletRequest request) throws Exception {
        LoginRedisObj loginObj = this.getUserObj(request);
        List<ExamModelSimpleVo> list = examModelService.classExamModelList(classId , loginObj.getOrganizationId() ,levelId , range_type , timeType ,activityId);
        return ReturnResult.success(list);
    }


    @ApiOperation(value = "活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(name = "keyword", value = "关键字", paramType = "query"),
            @ApiImplicitParam(name = "isUse", value = "是否启用", paramType = "query")
    })
    @RequestMapping(value = "/examModelActivityList", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<List<ExamModelActivity>> examModelActivityList(HttpServletRequest request,
                                                                       @Validated @ModelAttribute PageParams pageParams,
                                                                       String keyword,
                                                                       Integer isUse) throws Exception  {
        LoginRedisObj obj = this.getUserObj(request);
        Long authOrganizationId=obj.getOrganizationId();

        Map<String, Object> conditions = new HashMap<>();
        Pagination<ExamModelActivity> queryPgn = new Pagination<>();
        conditions.put("authOrganizationId", authOrganizationId);
        conditions.put("name", StringUtils.isEmpty(keyword) ? keyword:keyword.trim());
        conditions.put("isUse", isUse);
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = examModelService.findExamModelActivityCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            List<ExamModelActivity> list = examModelService.findExamModelActivityPageList(queryPgn);
            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }

    @ApiOperation(value = "新建活动")
    @RequestMapping(value = "/addExamModelActivity", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ExamModelActivity> addExamModelActivity(@Validated @ModelAttribute ExamModelActivityAdd examModelActivityAdd,
                                                HttpServletRequest request) {

        LoginRedisObj loginObj = this.getUserObj(request);
        ExamModelActivity examModelActivity = examModelService.addExamModelActivity(examModelActivityAdd, loginObj);
        return ReturnResult.success(examModelActivity);
    }

    @ApiOperation(value = "活动详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动 ID", paramType = "query", required = true)})
    @RequestMapping(value = "/detailExamModelActivity", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<ExamModelActivityDTO> detailExamModelActivity(@NotNull(message = "活动ID") Long id) {

        ExamModelActivityDTO examModelActivity = examModelActivityMapper.selectByPrimaryKey(id);
        return ReturnResult.success(examModelActivity);
    }

    @ApiOperation(value = "编辑活动")
    @RequestMapping(value = "/editExamModelActivity", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<String> editExamModelActivity(@Validated @ModelAttribute ExamModelActivityEdit examModelActivityEdit,
                                                      HttpServletRequest request) {

        LoginRedisObj loginObj = this.getUserObj(request);
        examModelService.editExamModelActivity(examModelActivityEdit, loginObj);
        return ReturnResult.success("OK");
    }


    @ApiOperation(value = "试卷模板详情-录分更换试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷模板ID", paramType = "query", required = true),
            @ApiImplicitParam(name = "stuId", value = "学生ID", paramType = "query", required = true)})
    @RequestMapping(value = "/detailExamModelChange", method = { RequestMethod.GET,RequestMethod.POST })
    public ReturnResult<StudentRecordVo> detailExamModelChange(@NotNull(message = "试卷模板ID") Long id,
                                                               @NotNull(message = "学生ID")Long stuId) {

        StudentRecordVo s = examModelService.detailExamModelChange(id , stuId);
        return ReturnResult.success(s);
    }
}
